<template>
  <div class="chat-container">
    <!-- 左侧接待列表 -->
    <div class="reception-list">
      <div class="list-header">
        <h3>接待列表</h3>
        <div class="sort-selector">
          <select v-model="sortType" class="sort-select">
            <option v-for="option in sortOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
        </div>
      </div>
      <div class="list-tabs">
        <div 
          v-for="tab in tabs" 
          :key="tab.key"
          :class="['tab-item', { active: currentTab === tab.key }]"
          @click="currentTab = tab.key"
        >
          {{ tab.name }}
          <span class="count" v-if="userCount[tab.key]">{{ userCount[tab.key] }}</span>
        </div>
      </div>
      <div class="list-content">
        <VirtualList v-if="sortedUsers.length > 0" :users="sortedUsers" @select="selectUser" />
        <div v-else class="empty-list">暂无{{ tabs.find(t => t.key === currentTab).name }}用户</div>
      </div>
    </div>

    <!-- 中间聊天区域 -->
    <div class="chat-area">
      <template v-if="currentUser">
        <div class="chat-header">
          <div class="user-info">
            <span class="user-name">{{ currentUser.nickname }}</span>
          </div>
        </div>
        <div class="message-list" ref="messageList">
          <div v-for="(msg, index) in messages" :key="index" :class="['message-item', msg.from]">
            <div class="avatar">
              <img :src="msg.from === 'user' ? currentUser.avatar : '/agent-avatar.png'" alt="头像">
            </div>
            <div class="message-content">
              <div class="message-info">
                <span class="sender-name">{{ msg.from === 'user' ? currentUser.nickname : '客服' }}</span>
                <span class="message-time">{{ formatTime(msg.timestamp) }}</span>
              </div>
              <div class="message-text">{{ msg.content }}</div>
            </div>
          </div>
        </div>
        <div class="message-input">
          <div class="toolbar">
            <button class="tool-btn">表情</button>
            <button class="tool-btn">图片</button>
            <button class="tool-btn">文件</button>
          </div>
          <textarea 
            v-model="inputMessage" 
            placeholder="请输入消息..." 
            @keydown.enter.prevent="sendMessage"
          ></textarea>
          <div class="send-actions">
            <button class="send-btn" @click="sendMessage" :disabled="!inputMessage.trim()">发送</button>
          </div>
        </div>
      </template>
      <div v-else class="no-chat-selected">
        <div class="placeholder-text">请选择一个会话</div>
      </div>
    </div>

    <!-- 右侧客户资料 -->
    <div class="customer-profile">
      <template v-if="currentUser">
        <div class="profile-header">
          <h3>客户资料</h3>
          <button class="edit-btn" @click="isEditing = !isEditing">
            {{ isEditing ? '保存' : '编辑' }}
          </button>
        </div>
        <div class="profile-content">
          <div class="avatar-section">
            <div class="profile-avatar">
              <img :src="editedUser.avatar || '/default-avatar.png'" alt="客户头像">
            </div>
            <div v-if="isEditing" class="avatar-upload">
              <button class="upload-btn">更换头像</button>
            </div>
          </div>
          
          <div class="profile-fields">
            <div class="profile-field">
              <label>昵称</label>
              <input v-if="isEditing" v-model="editedUser.nickname" type="text">
              <span v-else>{{ currentUser.nickname }}</span>
            </div>
            <div class="profile-field">
              <label>来源渠道</label>
              <select v-if="isEditing" v-model="editedUser.source">
                <option value="website">官网</option>
                <option value="wechat">微信</option>
                <option value="app">APP</option>
                <option value="other">其他</option>
              </select>
              <span v-else>{{ sourceMap[currentUser.source] || '未知' }}</span>
            </div>
            <div class="profile-field">
              <label>接入时间</label>
              <span>{{ formatDateTime(currentUser.created_at) }}</span>
            </div>
            <div class="profile-field">
              <label>最后消息</label>
              <span>{{ currentUser.last_chat_msg || '暂无消息' }}</span>
            </div>
            <div class="profile-field">
              <label>最后消息时间</label>
              <span>{{ formatDateTime(currentUser.last_chat_time) }}</span>
            </div>
          </div>

          <div class="profile-notes">
            <label>备注信息</label>
            <textarea 
              v-if="isEditing" 
              v-model="editedUser.notes" 
              placeholder="添加客户备注..."
            ></textarea>
            <div v-else class="notes-content">{{ currentUser.notes || '暂无备注' }}</div>
          </div>
        </div>
      </template>
      <div v-else class="no-profile-selected">
        <div class="placeholder-text">请选择一个会话查看客户资料</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { useChatStore } from '../stores/chat';
import VirtualList from './UserList/VirtualList.vue';

const store = useChatStore();

// 标签页配置
const tabs = [
  { key: 'active', name: '接待中' },
  { key: 'waiting', name: '排队中' },
  { key: 'closed', name: '已接待' }
];

const currentTab = ref('active');
const currentUserId = ref('');
const inputMessage = ref('');
const messageList = ref(null);
const isEditing = ref(false);
const editedUser = ref({});

// 排序相关
const sortType = ref('last_chat_time_desc'); // 默认按最后聊天时间倒序
const sortOptions = [
  { value: 'last_chat_time_desc', label: '最近聊天优先' },
  { value: 'created_at_desc', label: '最近加入优先' },
  { value: 'created_at_asc', label: '最早加入优先' }
];

// 用户数量统计
const userCount = computed(() => {
  return {
    active: store.userGroups.active.size,
    waiting: store.userGroups.waiting.size,
    closed: store.userGroups.closed.size
  };
});

// 当前标签页的用户列表
const currentUsers = computed(() => {
  return Array.from(store.userGroups[currentTab.value].values());
});

// 排序后的用户列表
const sortedUsers = computed(() => {
  const users = [...currentUsers.value];
  
  switch (sortType.value) {
    case 'last_chat_time_desc':
      return users.sort((a, b) => new Date(b.last_chat_time || 0) - new Date(a.last_chat_time || 0));
    case 'created_at_desc':
      return users.sort((a, b) => new Date(b.created_at || 0) - new Date(a.created_at || 0));
    case 'created_at_asc':
      return users.sort((a, b) => new Date(a.created_at || 0) - new Date(b.created_at || 0));
    default:
      return users;
  }
});

// 当前选中的用户
const currentUser = computed(() => {
  if (!currentUserId.value) return null;
  return store.findUser(currentUserId.value);
});

// 模拟消息数据
const messages = ref([]);

// 等待时间计算
const userWaitTime = computed(() => {
  if (!currentUser.value || !currentUser.value.last_user_msg) return 0;
  return Math.floor((Date.now() - currentUser.value.last_user_msg) / 1000);
});

const agentWaitTime = computed(() => {
  if (!currentUser.value || !currentUser.value.last_agent_msg) return 0;
  return Math.floor((Date.now() - currentUser.value.last_agent_msg) / 1000);
});

// 来源渠道映射
const sourceMap = {
  website: '官网',
  wechat: '微信',
  app: 'APP',
  other: '其他'
};

// 选择用户
function selectUser(user) {
  currentUserId.value = user.id;
  // 重置编辑状态
  isEditing.value = false;
  // 加载用户消息
  loadUserMessages(user.id);
  // 初始化编辑表单
  editedUser.value = { ...user };
}

// 加载用户消息（模拟数据）
function loadUserMessages(userId) {
  // 这里应该从API获取消息历史
  messages.value = [
    {
      from: 'user',
      content: '您好，我想咨询一下产品的使用问题',
      timestamp: Date.now() - 3600000
    },
    {
      from: 'agent',
      content: '您好，很高兴为您服务，请问有什么可以帮到您的？',
      timestamp: Date.now() - 3500000
    },
    {
      from: 'user',
      content: '我在使用过程中遇到了一些问题，系统提示错误代码1001',
      timestamp: Date.now() - 3400000
    }
  ];
  
  // 滚动到底部
  setTimeout(() => {
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight;
    }
  }, 100);
}

// 发送消息
function sendMessage() {
  if (!inputMessage.value.trim() || !currentUser.value) return;
  
  // 添加新消息
  const newMessage = {
    from: 'agent',
    content: inputMessage.value,
    timestamp: Date.now()
  };
  
  messages.value.push(newMessage);
  
  // 更新最后消息时间
  store.updateUserLastChat(
    currentUser.value.id, 
    inputMessage.value,
    Date.now()
  );
  
  // 清空输入框
  inputMessage.value = '';
  
  // 滚动到底部
  setTimeout(() => {
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight;
    }
  }, 100);
}

// 格式化时间
function formatTime(timestamp) {
  const date = new Date(timestamp);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}

// 格式化日期时间
function formatDateTime(timestamp) {
  if (!timestamp) return '未知';
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}

// 监听用户变化，重置编辑状态
watch(currentUser, (newUser) => {
  if (newUser) {
    editedUser.value = { ...newUser };
  }
});
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
  background-color: #f5f7fa;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

/* 左侧接待列表样式 */
.reception-list {
  width: 280px;
  border-right: 1px solid #e0e3e9;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.list-header {
  padding: 16px;
  border-bottom: 1px solid #e0e3e9;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.sort-selector {
  display: flex;
  align-items: center;
}

.sort-select {
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
  background-color: #fff;
  cursor: pointer;
  outline: none;
}

.sort-select:hover {
  border-color: #1890ff;
}

.sort-select:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}
.list-tabs {
  display: flex;
  border-bottom: 1px solid #e0e3e9;
}

.tab-item {
  flex: 1;
  padding: 12px 8px;
  text-align: center;
  cursor: pointer;
  font-size: 14px;
  position: relative;
}

.tab-item.active {
  color: #1890ff;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40%;
  height: 2px;
  background-color: #1890ff;
}

.count {
  display: inline-block;
  margin-left: 4px;
  background-color: #f0f2f5;
  border-radius: 10px;
  padding: 0 6px;
  font-size: 12px;
  line-height: 16px;
}

.list-content {
  flex: 1;
  overflow-y: auto;
}

.empty-list {
  padding: 40px 0;
  text-align: center;
  color: #999;
  font-size: 14px;
}

/* 中间聊天区域样式 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-right: 1px solid #e0e3e9;
}

.chat-header {
  padding: 12px 16px;
  border-bottom: 1px solid #e0e3e9;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-name {
  font-size: 16px;
  font-weight: 500;
  margin-right: 12px;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 4px 12px;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  background-color: #fff;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.action-btn.danger {
  color: #ff4d4f;
  border-color: #ff4d4f;
}

.action-btn.danger:hover {
  background-color: #fff1f0;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f5f7fa;
}

.message-item {
  display: flex;
  margin-bottom: 16px;
}

.message-item.agent {
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-content {
  max-width: 70%;
  margin: 0 12px;
}

.message-item.agent .message-content {
  text-align: right;
}

.message-info {
  margin-bottom: 4px;
  font-size: 12px;
  color: #999;
}

.sender-name {
  margin-right: 8px;
}

.message-text {
  padding: 10px 14px;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  word-break: break-word;
  line-height: 1.5;
}

.message-item.agent .message-text {
  background-color: #e6f7ff;
}

.message-input {
  border-top: 1px solid #e0e3e9;
  padding: 12px 16px;
}

.toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.tool-btn {
  padding: 4px 8px;
  border: none;
  background: none;
  font-size: 14px;
  color: #666;
  cursor: pointer;
}

.tool-btn:hover {
  color: #1890ff;
}

textarea {
  width: 100%;
  height: 80px;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  resize: none;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.5;
}

textarea:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.send-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

.send-btn {
  padding: 6px 16px;
  border: none;
  border-radius: 4px;
  background-color: #1890ff;
  color: #fff;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.send-btn:hover {
  background-color: #40a9ff;
}

.send-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.no-chat-selected {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.placeholder-text {
  color: #999;
  font-size: 16px;
}

/* 右侧客户资料样式 */
.customer-profile {
  width: 300px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

.profile-header {
  padding: 16px;
  border-bottom: 1px solid #e0e3e9;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.edit-btn {
  padding: 4px 12px;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  background-color: #fff;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.edit-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.profile-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.profile-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  margin-bottom: 12px;
}

.profile-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-upload {
  margin-top: 8px;
}

.upload-btn {
  padding: 4px 12px;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  background-color: #fff;
  font-size: 14px;
  cursor: pointer;
}

.profile-fields {
  margin-bottom: 20px;
}

.profile-field {
  margin-bottom: 16px;
}

.profile-field label {
  display: block;
  margin-bottom: 6px;
  font-size: 14px;
  color: #666;
}

.profile-field input,
.profile-field select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
}

.profile-field input:focus,
.profile-field select:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.profile-notes {
  margin-top: 20px;
}

.profile-notes label {
  display: block;
  margin-bottom: 6px;
  font-size: 14px;
  color: #666;
}

.profile-notes textarea {
  width: 100%;
  height: 100px;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  resize: none;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.5;
}

.profile-notes textarea:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.notes-content {
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  min-height: 80px;
  line-height: 1.5;
}

.no-profile-selected {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>